package medium;

/**
 * @author shizhun
 * @description:
 * @date 2025/9/9 10:03
 * @see DeviceEntity
 */
public class T7 {
    static long gg;

    public static void main(String[] args) {
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Integer.MAX_VALUE);
        System.out.println(new T7().reverse(-2147483648));
    }

    public int reverse(int x) {
        if (x == Integer.MIN_VALUE){
            return 0;
        }
        gg = x;
        // 长度是否小于32位
        // 小于32位，直接反转得到结果
        // 等于32位，判断最后一位数是否大于32位最大值的第一位
        boolean isPositive = false;
        if (x >= 0) {
            isPositive = true;
        } else {
            x = -x;
        }
        int x_copy = x;
        int len = 0;
        while (x > 0) {
            x /= 10;
            len++;
        }
        int result;
        if (len < 10) {
            result = getResult();
        } else {
            result = compareFirst(x_copy, Integer.MAX_VALUE, len);
        }

        if (!isPositive) {
            result = -result;
        }
        return result;

    }

    public int compareFirst(int x, int y, int len) {
        int i = x % 10;
        int j = (int) (y / Math.pow(10, len - 1) % 10);
        if (i < j) {
            return getResult();
        } else if (i == j) {
            // 继续循环
            return compareFirst(x / 10, y, len - 1);
        } else {
            return 0;
        }
    }

    public int getResult() {
        long result = 0;
        if (gg<0){
            gg = -gg;
        }
        while (gg > 0) {
            result *= 10;
            long current = gg % 10;
            result += current;
            gg /= 10;
        }
        return (int) result;
    }
}
